import types from '../types'
import common from '../common'
import store from '../index.js'
import axios from 'axios'
import moment from 'moment'
import env from '@/config/env'
import {apiGetSign} from '@/service/apiService'
import {apiGetUserAcct, apiAsyncSnd2Acct, apiSnd2Acct} from '@/service/apiAcct'
import {custsign, custsign2, createSignData} from '@/myutl/utlenc'

const state = {
  acctInf: {},        // 用户账户信息
  acctDtls: [],
  amtTr: 0,           // 交易金额(单位:分)
  acctNum: -2,        // -2:未获取账户信息 -1:获取失败 0:账户不存在 1:成功获取信息
  acctRetSucc: false,
  acctErrcd: null,
  acctErrmsg: null
}

const getters = {
  acctInf(state) {
    return state.acctInf;
  },
  acctDtls(state) {
    return state.acctDtls;
  },
  amtTr(state) {
    return state.amtTr;
  },
  acctNum(state) {
    return state.acctNum;
  },
  acctRetSucc(state) {
    return state.acctRetSucc;
  },
  acctErrcd(state) {
    return state.acctErrcd;
  },
  acctErrmsg(state) {
    return state.acctErrmsg;
  }
}

const actions = {
  /**
   * [getAcct description]
   * @param  {[type]} options.commit [description]
   * @param  {[type]} options.state  [description]
   * @param  {[type]} qryCond        [查询条件]
   *                  |-custId       [客户号]
   *                  |-acctTpBiz    [账户业务类型]
   * @return {[type]}                [description]
   */
  async getAcct({commit,state}, qryCond) {
    let curTs = moment().format('YYYYMMDDHHmmss');

    let params = {
                  "appId": env.appId,
                  "charset": "utf-8",
                  "timestamp": curTs,
                  "version": "1.0",
                  "appAuthToken": store.getters.authToken ? store.getters.authToken : "",
                  "bizContent": {
                    "msgSsn": curTs,
                    "custId": qryCond.custId,
                    "custIdTp": "0",    // 0=会员号
                    "acctTpBiz": qryCond.acctTpBiz
                  }
                };
    let signData = createSignData(params);
    // console.log("createSignData:", signData);
    let retData = await apiGetSign(signData);
    if (retData.errno != 0) {
      commit(types.LOGIN_USER, {isLoginSucc: false, errmsg: "登录超时请重试"});
      return;
    }
    params.signType = "RSA2";
    params.sign = retData.sign;
    console.log("params:", params);

    apiAsyncSnd2Acct("/acct/accttxn_queryam", "get", params).then((rsp) => {
      console.log("apiAsyncSnd2Acct-then:", rsp.data);
      if (rsp.data.subCode === undefined  || rsp.data.subCode === null) {
        commit(types.GET_ACCT, {acctNum:-1, errmsg:rsp.data.msg});
      } else {
        console.log("rsp.data.subCode", rsp.data.subCode.substring(2));
        if (rsp.data.subCode.substring(2) === "0000") {
          let acctInf =  {
            "acctNo": rsp.data.acctNo,
            "acctBal": rsp.data.acctBalF,
            "acctSta": rsp.data.acctSta
          };
          commit(types.GET_ACCT, {acctNum:1, acctInf: acctInf});
        } else if (rsp.data.subCode.substring(2) === "AT01") {  // 账户不存在
          commit(types.GET_ACCT, {acctNum:0, errmsg:rsp.data.submsg});
        } else {
          commit(types.GET_ACCT, {acctNum:-1, errmsg:rsp.data.submsg});
        }
      } 
    });
  },
  async getAcctDtls({commit,state}, qryCond) {
      let curTs = moment().format('YYYYMMDDHHmmss');

      let params = {
                    "appId": env.appId,
                    "charset": "utf-8",
                    "timestamp": curTs,
                    "version": "1.0",
                    "appAuthToken": store.getters.authToken ? store.getters.authToken : "",
                    "bizContent": {
                      "msgSsn": curTs,
                      "custId": qryCond.custId,
                      "custIdTp": "0",    // 0=会员号
                      "acctTpBiz": qryCond.acctTpBiz,
                      "qryFlg": "1",      // 1=当月
                      "maxRetCnt": 100
                    }
                  };
      let signData = createSignData(params);
      // console.log("createSignData:", signData);
      let retData = await apiGetSign(signData);
      if (retData.errno != 0) {
        commit(types.LOGIN_USER, {isLoginSucc: false, errmsg: "登录超时请重试"});
        return;
      }
      params.signType = "RSA2";
      params.sign = retData.sign;
      console.log("params:", params);

      apiAsyncSnd2Acct("/acct/accttxn_querydtl", "get", params).then((rsp) => {
        retData = rsp.data;
        console.log("apiAsyncSnd2Acct-then:", retData);
        if (retData.subCode === undefined  || retData.subCode === null) {
          commit(types.GET_ACCT, {acctNum:-1, errmsg:rsp.data.msg});
        } else {
          console.log("retData.subCode", retData.subCode.substring(2));
          if (rsp.data.subCode.substring(2) === "0000") {
            console.log("rec size:", retData.bizContent.length);
            commit(types.GET_ACCTDTLS, {isRetSucc: true, errcd: retData.subCode, acctDtls: rsp.data.bizContent});
          }
          else {
            commit(types.GET_ACCT, {isRetSucc: false, errcd: retData.subCode, errmsg:rsp.data.submsg});
          }
        } 
      });
  },
  /**
   * [账户充值入账]
   * @param  {[type]} options.commit [description]
   * @param  {[type]} options.state  [description]
   * @param  {[type]} odrInf         [订单信息]
   *                  |-odrAmt       [订单金额]
   *                  |-subject      [订单标题]
   *                  |-acctTpBiz    [账户业务类型]
   * @return {[type]}                [description]
   */
  async depositin({commit,state}, odrInf) {
    let curTs = moment().format('YYYYMMDDHHmmss');

    let params = {
                  "appId": env.appId,
                  "charset": "utf-8",
                  "timestamp": curTs,
                  "version": "1.0",
                  "appAuthToken": store.getters.authToken ? store.getters.authToken : "",
                  "bizContent": {
                    "msgSsn": curTs,
                    "mchtCd": env.mchtCd,
                    "odrAmt": odrInf.odrAmt,
                    "subject": odrInf.subject ? odrInf.subject : "sbjt",
                    "custId": odrInf.custId,
                    "custIdTp": "0",      // 0=会员号 
                    "acctTpBiz": odrInf.acctTpBiz
                  }
                };
    let signData = createSignData(params);
    console.log("createSignData:", signData);
    let retData = await apiGetSign(signData);
    if (retData.errno != 0) {
      commit(types.MOD_ACCT, {isRetSucc: false, errmsg: "登录超时请重试"});
      return;
    }
    params.signType = "RSA2";
    params.sign = retData.sign;

    retData = await apiSnd2Acct("/acct/acctpay_depositin", "post", params);
    console.log("retData:", retData);
    if (retData.subCode === undefined  || retData.subCode === null) {
      commit(types.MOD_ACCT, {isRetSucc:false, errcd:retData.code, errmsg:retData.msg});
    } else {
      console.log("retData.subCode", retData.subCode.substring(2));
      console.log("retData.subMsg", retData.subMsg);
      if (retData.subCode.substring(2) === "0000") {
        let acctInf =  {
          "acctNo": retData.acctNo,
          "acctBal": retData.acctBalF
        };
        commit(types.MOD_ACCT, {isRetSucc:true, errcd:retData.subCode, acctInf: acctInf, amtTr: odrInf.odrAmt});
      } else if (rsp.data.subCode.substring(2) === "AT01") {  // 账户不存在
        commit(types.MOD_ACCT, {isRetSucc:false, errcd: retData.subCode, errmsg:retData.subMsg});
      } else {
        commit(types.MOD_ACCT, {isRetSucc:false, errcd: retData.subCode, errmsg:retData.subMsg});
      }
    } 

    // apiAsyncSnd2Acct("/acct/acctpay_depositin", "post", params).then((rsp) => {
    //   console.log("apiAsyncSnd2Acct-then:", rsp.data);
    //   if (rsp.data.subCode === undefined  || rsp.data.subCode === null) {
    //     commit(types.MOD_ACCT, {isRetSucc:false, errcd:rsp.data.code, errmsg:rsp.data.msg});
    //   } else {
    //     console.log("rsp.data.subCode", rsp.data.subCode.substring(2));
    //     console.log("rsp.data.subMsg", rsp.data.subMsg);
    //     if (rsp.data.subCode.substring(2) === "0000") {
    //       let acctInf =  {
    //         "acctNo": rsp.data.acctNo,
    //         "acctBal": rsp.data.acctBalF
    //       };
    //       commit(types.MOD_ACCT, {isRetSucc:true, errcd:rsp.data.subCode, acctInf: acctInf});
    //     } else if (rsp.data.subCode.substring(2) === "AT01") {  // 账户不存在
    //       commit(types.MOD_ACCT, {isRetSucc:false, errcd: rsp.data.subCode, errmsg:rsp.data.subMsg});
    //     } else {
    //       commit(types.MOD_ACCT, {isRetSucc:false, errcd: rsp.data.subCode, errmsg:rsp.data.subMsg});
    //     }
    //   } 
    // }).catch((err) => {
    //   if (err.response) {
    //     // The request was made and the server responded with a status code
    //     // that falls out of the range of 2xx
    //     console.error("err:", err.response.status, err.response.data);
    //     // console.log("response.status:", err.response.status);
    //     // console.log("err.response.headers:", err.response.headers);
    //     commit(types.MOD_ACCT, {isRetSucc:false, errcd: err.response.status, errmsg:err.response.data});
    //   } else if (err.request) {
    //     // The request was made but no response was received
    //     // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
    //     // http.ClientRequest in node.js
    //     console.error(err.request);
    //   } else {
    //     // Something happened in setting up the request that triggered an Error
    //     console.error('Error', err.message);
    //   }
    //   // console.log(err.config);
    // });
  },
  /**
   * [账户支付]
   * @param  {[type]} options.commit [description]
   * @param  {[type]} options.state  [description]
   * @param  {[type]} odrInf         [订单信息]
   *                  |-odrAmt       [订单金额]
   *                  |-subject      [订单标题]
   *                  |-acctTpBiz    [账户业务类型]
   * @return {[type]}                [description]
   */
  async pay({commit,state}, odrInf) {
    let curTs = moment().format('YYYYMMDDHHmmss');

    let params = {
                  "appId": appId,
                  "charset": "utf-8",
                  "timestamp": curTs,
                  "version": "1.0",
                  "appAuthToken": store.getters.authToken ? store.getters.authToken : "",
                  "bizContent": {
                    "msgSsn": curTs,
                    "mchtOdrId": "ODR" + curTs,
                    "mchtCd": mchtCd,
                    "odrAmt": odrInf.odrAmt,
                    "subject": odrInf.subject ? odrInf.subject : "sbjt",
                    "custId": odrInf.custId,
                    "custIdTp": "0",      // 0=会员号 
                    "acctTpBiz": odrInf.acctTpBiz
                  }
                };
    let signData = createSignData(params);
    console.log("createSignData:", signData);
    let retData = await apiGetSign(signData);
    if (retData.errno != 0) {
      commit(types.MOD_ACCT, {isRetSucc: false, errmsg: "登录超时请重试"});
      return;
    }
    params.signType = "RSA2";
    params.sign = retData.sign;

    retData = await apiSnd2Acct("/acct/accttxn_trade_pay", "post", params);
    console.log("retData:", retData);
    if (retData.subCode === undefined  || retData.subCode === null) {
      commit(types.MOD_ACCT, {isRetSucc:false, errcd:retData.code, errmsg:retData.msg});
    } else {
      console.log("retData.subCode", retData.subCode.substring(2));
      console.log("retData.subMsg", retData.subMsg);
      if (retData.subCode.substring(2) === "0000") {
        let acctInf =  {
          "acctNo": retData.acctNo,
          "acctBal": retData.acctBalF
        };
        commit(types.MOD_ACCT, {isRetSucc:true, errcd:retData.subCode, acctInf: acctInf, amtTr: odrInf.odrAmt});
      } else if (rsp.data.subCode.substring(2) === "AT01") {  // 账户不存在
        commit(types.MOD_ACCT, {isRetSucc:false, errcd: retData.subCode, errmsg:retData.subMsg});
      } else {
        commit(types.MOD_ACCT, {isRetSucc:false, errcd: retData.subCode, errmsg:retData.subMsg});
      }
    }
  }
}

const mutations = {
  [types.GET_ACCT](state, data) {
    console.log("GET_ACCT-data:", data);
    if (data.acctNum > 0) {
      state.acctInf = data.acctInf;
      state.acctNum = data.acctNum;
    } else {
      state.acctNum = data.acctNum;
      state.acctErrmsg = data.errmsg;
    }
  },
  [types.GET_ACCTDTLS](state, data) {
    console.log("GET_ACCTDTLS-data:", data);
    state.acctErrcd = data.errcd;
    if (data.isRetSucc) {
      state.acctDtls = data.acctDtls;
      state.amtTr = data.amtTr;
    } else {
      state.acctErrmsg = data.errmsg;
    }
  },
  [types.MOD_ACCT](state, data) {
    console.warn("MOD_ACCT-data:", data);
    state.acctErrcd = data.errcd;
    if (data.isRetSucc) {
      state.acctDtls = data.acctDtl;
    } else {
      state.acctErrmsg = data.errmsg;
    }
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
